import datetime
import pandas as pd
import re


class BuildMatrix:  # FATP Matrix Only!

    def __init__(self, path):
        self.path = path
        dfs = pd.read_excel(path, sheet_name=None)
        self.version = float(dfs['FATP Changelist'].iloc[0, 0][1:])
        # c = re.compile('Project:(?P<Project>.*)Build Stage:(?P<Stage>.*)Build: FATP(.*)By:(?P<name>.*)on:(?P<Date>.*)')
        # result = re.match(c, str(dfs['FATP'].columns[0]).strip())
        # self.project = result.group('Project').strip()
        # self.build_stage = result.group('Stage').strip()
        # self.publisher = result.group('name').strip()
        # self.date = datetime.datetime.strptime(result.group('Date').strip(), '%Y-%m-%d %H:%M:%S')
        df = dfs['FATP']


        # locate  config(2,80)
        config_loc = ()
        for i in range(0, df.shape[0]):
            flag = 0
            for j in range(0, df.shape[1]):
                if str(df.iloc[i, j]).lower().strip() == 'configs':
                    config_loc = (i, j)
                    flag = 1
                    break
            if flag:
                break
        # locate  material(53,1)
        material_loc = ()
        for j in range(0, df.shape[1]):
            flag = 0
            for i in range(0, df.shape[0]):
                if str(df.iloc[i, j]).lower().strip() == 'component':
                    material_loc = (i, j)
                    flag = 1
                    break
            if flag:
                break
        # material df
        material_df = df.iloc[material_loc[0]:]
        material_df.columns = material_df.iloc[0]
        material_df = pd.DataFrame(material_df)
        material_df['Component'] = material_df['Component'].fillna(method='ffill')
        material_df = material_df.iloc[2:]
        material_df.reset_index(inplace=True, drop=True)
        self.material_df = pd.DataFrame(material_df)
        self._component_loc = {}
        for i, cell in enumerate(material_df['Component']):
            if cell in self._component_loc:
                self._component_loc[cell].append(i)
            else:
                self._component_loc[cell] = [i]
        # config df

        config_df = df.iloc[config_loc[0]:material_loc[0], config_loc[1]:]
        config_df = pd.DataFrame(config_df)
        # df第一行的所有值
        config_df.columns = config_df.iloc[0]
        # df的第一列的所有值
        config_df.index = config_df.iloc[:, 0]

        config_df = config_df.iloc[1:, 1:]
        # 過濾掉Build Date中無數據的對應列
        config_df.drop(columns=[col for col in config_df.columns if pd.isnull(config_df.loc['Build Date', col])],
                       inplace=True)

        config_df.columns.name = 'Config'
        self.config_df = pd.DataFrame(config_df)
        self.configs = set(self.config_df.columns)
        # self.input_dates = set([datetime.datetime.strptime(_, '%m/%d/%Y') for _ in self.config_df.loc['Build Date', :]])


    # def __str__(self):
    #     return f'BuildMatrix Version:{self.version} PROJECT:{self.project} STAGE:{self.build_stage} DATE:{self.date}'


    def query_material(self, name, config, item='Vendor'):
        """
        query material df
        :param name: component name
        :param config: config
        :param item: item name
        :return:
        """
        try:
            for i in self._component_loc[name]:
                if not pd.isna(self.material_df.loc[i, config]):
                    return self.material_df.loc[i, item]
        except:
            # return '无该料件'
            return

    def query_config(self, config, item):
        """
        query config df
        :param item: item name
        :param config: config
        :return:
        """
        try:
            return self.config_df.loc[item, config]
        except:
            return None

#
# matrix = BuildMatrix('/Users/user/PycharmProjects/text1/build_martix/'
#                      'Everest (ICT) Engineering Builds Proto 1 FATP ICT Build Matrix (v20.0) 1020 0838.xlsx')
#
# print(matrix)

class MatrixForPAM:
    def __init__(self, path):
        self.path = path
        dfs = pd.read_excel(path, sheet_name=None)
        self.version = float(dfs['PAM Changelist'].iloc[0, 0][1:])
        # c = re.compile('Project:(?P<Project>.*)Build Stage:(?P<Stage>.*)Build: PAM(.*)By:(?P<name>.*)on:(?P<Date>.*)')
        # result = re.match(c, str(dfs['PAM'].columns[0]).strip())
        # self.project = result.group('Project').strip()
        # self.build_stage = result.group('Stage').strip()
        # self.publisher = result.group('name').strip()
        # self.date = datetime.datetime.strptime(result.group('Date').strip(), '%Y-%m-%d %H:%M:%S')
        df = dfs['PAM']
        config_loc = ()
        for i in range(0, df.shape[0]):
            flag = 0
            for j in range(0, df.shape[1]):
                if str(df.iloc[i, j]).lower().strip() == 'configs':
                    config_loc = (i, j)
                    flag = 1
                    break
            if flag:
                break

        # locate  material(53,1)
        material_loc = ()
        for j in range(0, df.shape[1]):
            flag = 0
            for i in range(0, df.shape[0]):
                if str(df.iloc[i, j]).lower().strip() == 'component':
                    material_loc = (i, j)
                    flag = 1
                    break
            if flag:
                break
        # material df
        material_df = df.iloc[material_loc[0]:]
        material_df.columns = material_df.iloc[0]
        material_df = pd.DataFrame(material_df)
        material_df['Component'] = material_df['Component'].fillna(method='ffill')
        material_df = material_df.iloc[2:]
        material_df.reset_index(inplace=True, drop=True)
        self.material_df = pd.DataFrame(material_df)
        self._component_loc = {}
        for i, cell in enumerate(material_df['Component']):
            if cell in self._component_loc:
                self._component_loc[cell].append(i)
            else:
                self._component_loc[cell] = [i]
        # config df

        config_df = df.iloc[config_loc[0]:material_loc[0], config_loc[1]:]

        config_df = pd.DataFrame(config_df)
        # df第一行的所有值
        config_df.columns = config_df.iloc[0]
        # df的第一列的所有值
        config_df.index = config_df.iloc[:, 0]

        config_df = config_df.iloc[1:, 1:]
        # 過濾掉Build Date中無數據的對應列
        config_df.drop(columns=[col for col in config_df.columns if pd.isnull(config_df.loc['Build Date', col])],
                       inplace=True)

        config_df.columns.name = 'Config'
        self.config_df = pd.DataFrame(config_df)

        self.configs = set(self.config_df.columns)

    #     self.input_dates = set([datetime.datetime.strptime(_, '%m/%d/%Y') for _ in self.config_df.loc['Build Date', :]])
    #
    # def __str__(self):
    #     return f'BuildMatrix Version:{self.version} PROJECT:{self.project} STAGE:{self.build_stage} DATE:{self.date}'

    def query_material(self, name, config, item):
        """
        query material df
        :param name: component name
        :param config: config
        :param item: item name
        :return:
        """
        for i in self._component_loc[name]:
            if self.material_df.loc[i, config] == 'x':
                return self.material_df.loc[i, item]

    def query_config(self, config, item):
        """
        query config df
        :param item: item name
        :param config: config
        :return:
        """
        return self.config_df.loc[item, config]
